playOb = document.getElementById('audio');
xhr = new XMLHttpRequest();
if (playOb == null) {
    console.log("创建audio对象");
    playOb = new Audio();
}
playOb.autoplay = true;
playOb.controls = true;
playOb.loop = true;
// songNewTable.isReady().then(() => {
//     console.log(songNewTable.read(0));
// })


var canvas = document.getElementById("canvas");
console.log(canvas);
var ctx = canvas.getContext("2d");
canvas.addEventListener( 
    "mousemove", function(event) { 
    MouseMoveCheck(event); 
})
canvas.addEventListener( "mousedown",function (event) {
    console.log(event.button);
}); 


//绘制矩形


// ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
// ctx.fillRect (30, 30, 55, 50);
// ctx.strokeRect(10, 70, 100, 50);

chrome.runtime.onMessage.addListener(handleMessage); 

function MouseMoveCheck(event){
    console.log(event);
    const img = new Image();
    img.src = "../pic/background.jpg"
    const element =document.documentElement;
    const bounds = element.getBoundingClientRect();
    canvas.width = bounds.width;
    canvas.height = bounds.height;
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    var x = event.clientX
    var y = event.clientY;
    canvas.style.cursor = "crosshair";
    ctx.fillStyle = "rgb(255,255,0,0)";
    ctx.font = "8px ";
    // ctx.fillRect (x, y, 55, 50);
    ctx.fillStyle = "rgba(0, 0, 0, 0.9)";
    // ctx.strokeRect(x, y, 100, 50);
    ctx.strokeRect(x, y, 150, 150)
    ctx.drawImage(img, x, y, 100, 100);
    ctx.fillText("X:"+x, x , y+110);
    ctx.fillText("Y:"+y, x +50, y+110);

}

function handleMessage(msg,request,callback) {
    
    let playInfo = {}
    
    var playIndex = 0;
    var playName = null;
    var playPath = null;
    var playStatus = null;
    var actionInfo = "";
    try{
        console.log("options",msg,request);
    }catch (exception) {
        console.log("获取消息失败");
    }

    if (request.eventType == "MenuClick"){
        actionInfo = request.greeting.menuItemId
    }else if (request.eventType == "command"){
        actionInfo = request.greeting
    }
    // AddPlayStatus("options "+actionInfo);
    chrome.storage.sync.get('playMusic', (res) => {
        console.log(res);
        

    })
    
 


    if (playOb.readyState == 0) {
        console.log("当前未播放，清除缓存");
        chrome.storage.sync.clear();
    }

    if (song_list.length == 0){
        const s = GetMusicList();
        console.log(s);
    }


    callback({message: "Hello from options"});
    
}


chrome.storage.onChanged.addListener(function(changes, namespace) {
    for (var key in changes) {
        var storageChange = changes[key];
        console.log('Storage key "%s" in namespace "%s" changed. ' +'Old value was "%s", new value is "%s".',
        key,
        namespace,
        storageChange.oldValue,
        storageChange.newValue);
    }
});


// chrome.runtime.sendMessage(
//     {greeting:"ready",from:"options"},
//     function(response) {
//         // console.log(chrome.fileSystem);
//         console.log(response);
//     }
// )

// try {
//     var windows = chrome.extension.getViews();
//     for (var extensionWindow of windows) {
        
//         if (extensionWindow.location.pathname === "/_generated_background_page.html") {
//             $(".change_px12").click(function () {
//                 var page = chrome.extension.getBackgroundPage();
//                 page.change_px12(); 
//             })
//         }
//     }

// }catch(error){
//     console.log(error);
// }

function AddPlayStatus(msg){
    chrome.storage.local.set({'playMusic' : msg,'platfrom':"options"}, () => {
        console.log('set successed!');
    });
    chrome.storage.sync.set({'playMusic' : msg,'platfrom':"options"}, () => {
        console.log('set successed!');
    });
}


function GetMusicList(){
    window.indexedDB.deleteDatabase('localMusic')
    console.log("获取音乐列表");
    const songbaseTable = {
    baseName: 'localMusic', // 数据库名称
    sheetName: 'songs', // 数据表名称
    keyName: 'songName', // 主键
    indexArr: [
            {name: 'songName', unique: true},
            {name: 'songPath', unique: false},
            {name: 'songDesc', unique: false}
        ] // 索引
    }
    // if  (song_list.ength != 0){
    //     console.log("歌曲已获取过");
    //     return 
    // }

    
    xhr.timeout = 3000;
    xhr.open('GET', 'http://localhost:1987/getMyMusic', true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4 && xhr.status === 200) {
            const responseData = JSON.parse(xhr.responseText); 
            var newList = document.createElement("select");
            newList.setAttribute('id', 'selectId');
            
            newList.size = "20";
            let {code,msg,songs} = responseData;
            // console.log(code,msg,songs);
            var songNewTable = new IndexedMyDB(songbaseTable);

            for(let i = 0;i< songs.length;i++){
                let song = songs[i];
                song_list.push(song);
                // newList.appendChild(new Option(song.name,song.path));
                var opt = new Option(song.name, song.path)
                newList.options.add(opt);
                // console.log(song);
                songNewTable.isReady().then(() => {
                    songNewTable.update({
                        songName: song.name,
                        songPath: song.path
                    })
                }).then(() => {
                    songNewTable.destroy()
                }).catch(e=> {
                    console.error(e)
                })
            }

            newList.onchange = function (item) {
                // showDiv('other');
                var selectId = document.getElementById("selectId");
                var index = selectId.selectedIndex
                playOb.src = "http://localhost:1987/music"+songs[index].path;
            }
            newList.onselect = function(item) {
                // showDiv('other');
                console.log("onselect"+item);
            }
            newList.onclick = function(item) {
                // showDiv('other');
                console.log(item);
            }
            chrome.storage.sync.get('playMusic', (res) => {
                console.log(res);
                if ((res.playMusic == undefined || res.playMusic == "pause")  && song_list.length > 0){
                    playOb.src = "http://localhost:1987/music"+song_list[theSongIndex].path;
                    console.log("开始播放"+song_list[0].name);
                    sendmessage("开始播放"+song_list[0].name);
                    playPath = song_list[theSongIndex].path;
                    playName = song_list[0].name;
                    playStatus = "play";
                    Play();
                    AddPlayStatus("play");
                }
            })
        }else{
            console.log("出现异常",xhr.readyState,xhr.status)
            return 3
        }
    };
    xhr.ontimeout = function(event){
        alert('请求超时！');
        return 2
    }
    xhr.send();
    return 1
}